package com.vipboot.platform.system.crud.service.monitor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vipboot.framework.core.util.MapStructUtil;
import com.vipboot.framework.core.util.StringUtil;
import com.vipboot.framework.mybatisplus.core.page.PageData;
import com.vipboot.framework.mybatisplus.core.page.PageQuery;
import com.vipboot.platform.system.crud.dao.SysLoginLogDao;
import com.vipboot.platform.system.domain.bo.SysLoginLogBo;
import com.vipboot.platform.system.domain.entity.SysLoginLog;
import com.vipboot.platform.system.domain.vo.SysLoginLogVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Service
public class SysLoginLogService {
    private final SysLoginLogDao sysLoginLogDao;

    public PageData<SysLoginLogVo> page(SysLoginLogBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysLoginLog> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtil.isNotBlank(bo.getIp()), SysLoginLog::getIp, bo.getIp())
                .eq(StringUtil.isNotBlank(bo.getStatus()), SysLoginLog::getStatus, bo.getStatus())
                .like(StringUtil.isNotBlank(bo.getUserName()), SysLoginLog::getUserName, bo.getUserName())
                .between(params.get("beginTime") != null && params.get("endTime") != null,
                        SysLoginLog::getLoginTime, params.get("beginTime"), params.get("endTime"));
        if (StringUtil.isBlank(pageQuery.getOrderByColumn())) {
            pageQuery.setOrderByColumn("id");
            pageQuery.setIsAsc("desc");
        }
        Page<SysLoginLogVo> page = sysLoginLogDao.pageVo(pageQuery.build(), lqw, SysLoginLogVo.class);
        return PageData.build(page);
    }

    public boolean save(SysLoginLogBo bo) {
        SysLoginLog entity = MapStructUtil.convert(bo, SysLoginLog.class);
        entity.setLoginTime(DateUtil.date());
        return sysLoginLogDao.save(entity);
    }
}
